package org.jeecg.trace.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.jeecg.trace.dto.BarCodeTraceDTO;
import org.jeecg.trace.dto.MaterialHistoryDTO;
import org.jeecg.trace.dto.ProcHistoryDTO;
import org.jeecg.trace.dto.QisDefectsDTO;
import org.jeecg.trace.entity.*;
import org.jeecg.trace.mapper.BarCodeTraceMapper;
import org.jeecg.trace.service.BarCodeTraceService;
import org.jeecg.trace.service.IMesProcDataValueService;
import org.jeecg.trace.service.IMesUnitHistoryService;
import org.jeecg.trace.service.IMesUnitStatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class BarCodeTraceServiceImpl implements BarCodeTraceService {
    @Autowired
    private IMesUnitStatusService iMesUnitStatusService;
    @Autowired
    private IMesUnitHistoryService iMesUnitHistoryService;
    @Autowired
    private IMesProcDataValueService iMesProcDataValueService;
    @Autowired
    private BarCodeTraceMapper barCodeTraceMapper;
    @Override
    public IPage<?> queryByCode(Page<BarCodeTraceDTO> page, String code) {
        //查询此条码对应的产品码
        IPage<BarCodeTraceDTO> product = barCodeTraceMapper.queryByCode(page,code);
        if (Objects.isNull(product)){
            Page<MesUnitStatus> statusPage = new Page<>(page.getPages(), page.getSize());
            IPage<MesUnitStatus> list = iMesUnitStatusService.page(statusPage,new LambdaQueryWrapper<MesUnitStatus>().eq(MesUnitStatus::getUnitsn, code));
            list.getRecords().forEach(item->{
                item.setFederationId(item.getLine()+"-"+item.getUnitsn());
            });
            return list;
        }

        return product;
    }

    @Override
    public IPage<MesUnitHistory> listMesUnitHistoryByUnitsn(Page<MesUnitHistory> page,String unitsn,String line) {
        List<String> list = getChildrenCode(unitsn);
        //2.查找所有子类条码的生产历史
        QueryWrapper<MesUnitHistory> queryWrapper = new QueryWrapper<MesUnitHistory>().in("UNITSN", list)
                .eq("line",line)
                .orderByAsc("CTIME");

        return iMesUnitHistoryService.page(page,queryWrapper);
    }

    public static void main(String[] args) {

        String smbFileUrl = "24BA012402071366";
        String substring = "23JB03" + smbFileUrl.substring(6);
        System.out.println(substring);
//        SmbFile smbFile;
//        try {
//            smbFile = new SmbFile(smbFileUrl);
//            if (!smbFile.exists()) {
//            } else {
//                SmbFile[] files = smbFile.listFiles();
//            }
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (SmbException e) {
//            e.printStackTrace();
//        }
    }
    @Override
    public IPage<MesProcDataValue> listMesProcDataValueByMainId(Page<MesProcDataValue> page, String mainId) {
        IPage<MesProcDataValue> pageList = iMesProcDataValueService.listMesProcDataValueByMainId(page,mainId);
        return pageList;
    }

    @Override
    public void exportXsl(HttpServletRequest request, HttpServletResponse response, BarCodeTraceDTO barCodeTraceDTO) {
        //定义easyExcel导出的对象
        ExcelWriter excelWriter = null;
        //内容样式策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //垂直居中,水平居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        // 字体策略
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short) 8);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        //头策略使用默认 设置字体大小
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 10);
        headWriteCellStyle.setWriteFont(headWriteFont);
        try {
            excelWriter = EasyExcel.write(response.getOutputStream()).build();
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=demo.xlsx");
            ExcelWriterSheetBuilder procHistory = EasyExcel.writerSheet(0, "产品加工历史");
            ExcelWriterSheetBuilder materialHistory = EasyExcel.writerSheet(1, "产品物料批次追溯");
            procHistory.head(ProcHistoryDTO.class)
                    .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle));
            materialHistory.head(MaterialHistoryDTO.class)
                    .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle));
            //查询数据并写入
            List<String> list = getChildrenCode(barCodeTraceDTO.getUnitsn());
            excelWriter.write(barCodeTraceMapper.queryProcHistoryByCode(list), procHistory.build());
            excelWriter.write(barCodeTraceMapper.queryMaterialHistoryByCode(list), materialHistory.build());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }

    }

    @Override
    public List<MaterialHistoryDTO> mesMaterialSetByProduct(Page<MesMaterialSet> page, String unitsn) {
        List<String> list = getChildrenCode(unitsn);
        return barCodeTraceMapper.queryMaterialHistoryByCode(list);
    }

    @Override
    public List<MesStatusbitCfg> listMesStatusWordValueByMainId(Page<MesMaterialSet> page, String historyId) {
        //根据历史id查询对应不良原因
        MesStatusWordValue mesStatusWordValue =barCodeTraceMapper.getMesStatusWordValueById(historyId);
        if(Objects.nonNull(mesStatusWordValue)){
            //根据对应的wordID找到对应的不良原因列表
            List<MesStatusbitCfg> mesStatusbitCfgList = barCodeTraceMapper.getMesStatusbitCfgList(mesStatusWordValue.getWordid());
            //获取不良原因进行分析
            String value = mesStatusWordValue.getValue();
            String binaryNumber = Integer.toBinaryString(Integer.parseInt(value));
            List<MesStatusbitCfg> list = new ArrayList<>();
            for(int i=0;i < binaryNumber.length();i++) {
                if(binaryNumber.charAt(i)=='1'){
                    String j = String.valueOf(i);
                    mesStatusbitCfgList.forEach(item->{
                        if (item.getBitpos().equals(j)){
                            item.setIsOK(true);
                        }
                    });
                }
            }
            return mesStatusbitCfgList;
        }else {
            return new ArrayList<MesStatusbitCfg>();
        }


    }

    @Override
    public List<QisDefectsDTO> listQisDefectsByMainId(String unitsn) {
        List<String> list = getChildrenCode(unitsn);
        return barCodeTraceMapper.listQisDefectsByMainId(list);
    }

    @Override
    public IPage<MesUnitid> listMesUnitIdByUnitsn(Page<MesUnitid> page, String unitsn) {
        List<String> list = getChildrenCode(unitsn);
        return barCodeTraceMapper.listMesUnitIdByUnitsn(page,list);
    }

    private List<String> getChildrenCode(String code) {
        List<String> list = new ArrayList<>();
        //1.递归查询主条码所有对应加工历史
        list.add(code);
        boolean isTrue = true;
        while (isTrue) {
            List<String> childrenList = barCodeTraceMapper.getChildrenCode(list);
            if (list.size() > 0) {
                AtomicInteger i = new AtomicInteger();
                childrenList.forEach(item -> {
                    if (!list.contains(item)) {
                        i.getAndIncrement();
                        list.add(item);
                    }
                });
                if (i.get() == 0) {
                    isTrue = false;
                }
            }
        }
        return list;
    }
}
